Introduction
Over the past few weeks, I have received several e-mails asking "How do I sort an array of strings in C++?" Well, I though about it for a few minutes, and came up with a "modified bubble sort" that does the sort using the stricmp() function. (Note: for those of you who are new to C or C++, stricmp() is part of the String Library - string.h, and it means "String Compare Ignore Case"). stricmp() will return a value of 1, 0 or -1 depending on the lexographic nature of the string. These are the values you use to perform the sort.
The Main Algorithm
As this can be incorperated as a seperate function or included in the function you are writing, I will include only the important parts of the algorithm. The rest will be left as an exercise.
for(i = 0; i < n-1; i++) for(j = n-1; j > i; --j) { // Allocate some temp space if(stricmp(*data[j], *data[j-1]) < 0) { char temp[80]; strcpy(temp, *data[j]); strcpy(*data[j], *data[j-1]); strcpy(*data[j-1], temp); } }
In this example, the variables i, j and n are cardinal integers, and n is the number of strings you are going to sort. Pretty simple!
Complexity
At best, the complexity of this is O(n2). I used bubble sort because it is easy to understand, but this concept could be applied to any sorting algorithm. The only thing you need to be concerned about is (a) how the compare's are performed: stricmp() and strcmp() will produce vastly different results, and (b) swapping the strings.